<?php

/**
 * @package account
 */

class BonusAccountHistoryReport extends SS_Report implements PermissionProvider {
	protected $sort = 10;
	
	public function title() {
		return _t('BonusAccountHistoryReport.TITLE', 'E-Bonus Transaction History Report');
	}
	
	/**
	 * @param Member $member
	 * @return boolean
	 */
	public function canView($member = null) {
		if(!$member && $member !== FALSE) {
			$member = Member::currentUser();
		}
		
		$extended = $this->extendedCan(__FUNCTION__, $member);
		if($extended !== null) return $extended;

        return Permission::check('VIEW_BonusAccountHistoryReport');
	}
	
	public function extendedCan($methodName, $member) {
		$results = $this->extend($methodName, $member);
		if($results && is_array($results)) {
			// Remove NULLs
			$results = array_filter($results, function($v) {return !is_null($v);});
			// If there are any non-NULL responses, then return the lowest one of them.
			// If any explicitly deny the permission, then we don't get access 
			if($results) return min($results);
		}
		return null;
	}
	
	public function sourceRecords($params, $sort, $limit) {
		if($sort) {
			$parts = explode(' ', $sort);
			$field = $parts[0];
			$direction = $parts[1];
			
			if($field == 'Name') {
			    $sort = 'FirstName ' . $direction;
			}
		}
        
        $ret = BonusAccount::get()->sort($sort)->limit($limit);

        if(isset($params['Type']) && $params['Type']){
            $ret = $ret->filter('Type', $params['Type']);
        }

		if(isset($params['Submit']) && $params['Submit']){
	        if(isset($params['StartDate']) && $params['StartDate']){
	        	$ret = $ret->filter('Date:GreaterThanOrEqual', DBField::create_field('Date', $params['StartDate'])->URLDate() . '00:00:00');
	        }
		}
		else{
			$ret = $ret->filter('Date:GreaterThanOrEqual', date('Y-m-01 00:00:00'));
		}
		
		if(isset($params['Submit']) && $params['Submit']){
			if(isset($params['EndDate']) && $params['EndDate']){
	        	$ret = $ret->filter('Date:LessThanOrEqual', DBField::create_field('Date', $params['EndDate'])->URLDate() . '23:59:59');
	        }
		}
		else{
			$ret = $ret->filter('Date:LessThanOrEqual', date('Y-m-t 23:59:59'));
		}
        
        if(isset($params['Username']) && $params['Username']){
        	$ret = $ret->filter('Member.Username:PartialMatch', $params['Username']);
        }
        
        if(isset($params['Reference']) && $params['Reference']){
        	$ret = $ret->filter('Reference:PartialMatch', $params['Reference']);
        }

		return $ret;
	}

	public function columns() {
		$fields = array(
            'Date' => array(
                'title' => _t('BonusAccountHistoryReport.DATE', 'Date'),
                'casting' => 'SS_Datetime->Nice'
            ),
            'Type' => array(
                'title' => _t('BonusAccountHistoryReport.TYPE', 'Type')
            ),
			'Username' => array(
				'title' => _t('BonusAccountHistoryReport.USERNAME', 'Username'),
                'formatting' => function($value, $item) {
                    return $item->Member()->Username;
                }
			),
			'Name' => array(
				'title' => _t('BonusAccountHistoryReport.NAME', 'Name'),
				'formatting' => function($value, $item) {
				    return $item->Member()->getName();
                }
			),
			'Reference' => array(
				'title' => _t('BonusAccountHistoryReport.REFERENCE', 'Reference')
			),
			'Description' => array(
				'title' => _t('BonusAccountHistoryReport.DESCRIPTION', 'Description')
			),
			'Credit' => array(
                'title' => _t('BonusAccountHistoryReport.IN', 'In'),
                'casting' => 'Decimal->Nice'
            ),
            'Debit' => array(
                'title' => _t('BonusAccountHistoryReport.OUT', 'Out'),
                'casting' => 'Decimal->Nice'
            ),
            'ForwardBalance' => array(
                'title' => _t('BonusAccountHistoryReport.BALANCE', 'Balance'),
                'casting' => 'Decimal->Nice'
            )
		);
		
		return $fields;
	}
	
	public function parameterFields() {
		return new FieldList(
			singleton('BonusAccountType')->getDropdownField('Type', _t('BonusAccountHistoryReport.TYPE', 'Type'))->setEmptyString(_t('BonusAccountHistoryReport.ALL', 'All')),
            FieldGroup::create(
            	DateField::create('filters[StartDate]', '', date('Y-m-01'))->addExtraClass('no-change-track'),
				DateField::create('filters[EndDate]', '', date('Y-m-t'))->addExtraClass('no-change-track')
			)->setTitle(_t('BonusAccountHistoryReport.DATE', 'Date')),
			UsernameField::create('Username', _t('BonusAccountHistoryReport.USERNAME', 'Username')),
			TextField::create('Reference', _t('BonusAccountHistoryReport.REFERENCE', 'Reference')),
			HiddenField::create('Submit', 'Submit', 1)
		);
	}

	public function providePermissions() {
        return array(
            'VIEW_BonusAccountHistoryReport' => array(
                'name' => _t('BonusAccountHistoryReport.PERMISSION_VIEW', 'Allow view access right ({title})', '', array('title' => $this->title())),
                'category' => _t('BonusAccountHistoryReport.PERMISSIONS_CATEGORY', 'Report')
            )
        );
    }
}
